import { query } from '../config/db.js';
import logger from '../config/logger.js';

/**
 * 获取所有权限
 */
const getPermissions = async (req, res) => {
  try {
    const result = await query('SELECT * FROM permissions');

    res.json({
      permissions: result.rows
    });
  } catch (error) {
    logger.error('获取权限列表错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 根据ID获取权限
 */
const getPermissionById = async (req, res) => {
  try {
    const { id } = req.params;

    const result = await query('SELECT * FROM permissions WHERE id = ?', [id]);

    if (result.rows.length === 0) {
      return res.status(404).json({
        message: '权限不存在'
      });
    }

    res.json({
      permission: result.rows[0]
    });
  } catch (error) {
    logger.error('根据ID获取权限错误:', error);
    res.status(500).json({
      message: 'Internal server error'
    });
  }
};

/**
 * 创建新权限
 */
const createPermission = async (req, res) => {
  try {
    const { name, description } = req.body;

    // 检查权限是否已存在
    const existingPermission = await query('SELECT * FROM permissions WHERE name = ?', [name]);

    if (existingPermission.rows.length > 0) {
      return res.status(400).json({
        message: '权限已存在'
      });
    }

    // 创建新权限
    await query(
      'INSERT INTO permissions (name, description) VALUES (?, ?)',
      [name, description]
    );

    // 获取创建的权限
    const selectResult = await query(
      'SELECT * FROM permissions WHERE name = ?',
      [name]
    );

    logger.info(`权限创建: ${selectResult.rows[0].name}`);

    res.status(201).json({
      message: '权限创建成功',
      permission: selectResult.rows[0]
    });
  } catch (error) {
    logger.error('创建权限错误:', error);
    res.status(500).json({
      message: 'Internal server error'
    });
  }
};

/**
 * 更新权限
 */
const updatePermission = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, description } = req.body;

    // 检查权限是否存在
    const existingPermission = await query('SELECT * FROM permissions WHERE id = ?', [id]);

    if (existingPermission.rows.length === 0) {
      return res.status(404).json({
        message: 'Permission not found'
      });
    }

    // 检查新名称是否已存在
    if (name && name !== existingPermission.rows[0].name) {
      const nameExists = await query('SELECT * FROM permissions WHERE name = ?', [name]);

      if (nameExists.rows.length > 0) {
        return res.status(400).json({
          message: '权限名称已存在'
        });
      }
    }

    // 准备更新字段
    const updateFields = [];
    const params = [];

    if (name) {
      updateFields.push('name = ?');
      params.push(name);
    }

    if (description) {
      updateFields.push('description = ?');
      params.push(description);
    }

    updateFields.push('updated_at = CURRENT_TIMESTAMP');
    params.push(id);

    // 更新权限
    await query(
      `UPDATE permissions SET ${updateFields.join(', ')} WHERE id = ?`,
      params
    );

    // 获取更新后的权限
    const selectResult = await query(
      'SELECT * FROM permissions WHERE id = ?',
      [id]
    );

    logger.info(`权限更新: ${selectResult.rows[0].name}`);

    res.json({
      message: '权限更新成功',
      permission: selectResult.rows[0]
    });
  } catch (error) {
    logger.error('更新权限错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 删除权限
 */
const deletePermission = async (req, res) => {
  try {
    const { id } = req.params;

    // Check if permission exists
    const existingPermission = await query('SELECT * FROM permissions WHERE id = ?', [id]);

    if (existingPermission.rows.length === 0) {
      return res.status(404).json({
        message: 'Permission not found'
      });
    }

    // 删除权限
    await query('DELETE FROM permissions WHERE id = ?', [id]);

    logger.info(`权限删除: ${existingPermission.rows[0].name}`);

    res.json({
      message: '权限删除成功'
    });
  } catch (error) {
    logger.error('删除权限错误:', error);
    res.status(500).json({
      message: 'Internal server error'
    });
  }
};

export {
  getPermissions,
  getPermissionById,
  createPermission,
  updatePermission,
  deletePermission
};